using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UniversalAdmin.Application.Dto;
using UniversalAdmin.Application.Commands;
using UniversalAdmin.Infrastructure.Data.Contexts;
using UniversalAdmin.Shared.Enums;
using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Entities.App;

namespace UniversalAdmin.Application.Services
{
    public class AppSystemConfigService : IAppSystemConfigService
    {
        private readonly AdminDbContext _db;
        public AppSystemConfigService(AdminDbContext db)
        {
            _db = db;
        }

        public async Task<ApiResult<IEnumerable<SystemConfigDto>>> GetAllAsync(string? search = null)
        {
            var query = _db.AppSystemConfigs.Where(c => !c.IsDelete);
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(c => c.Key.Contains(search) || (c.Value ?? "").Contains(search) || (c.Description ?? "").Contains(search));
            }
            var items = await query.OrderByDescending(c => c.CreatedAt)
                .Select(c => new SystemConfigDto
                {
                    Id = c.Id,
                    Key = c.Key,
                    Value = c.Value ?? string.Empty,
                    Description = c.Description,
                    IsActive = c.IsActive,
                    CreatedAt = c.CreatedAt,
                    UpdatedAt = c.UpdatedAt
                })
                .ToListAsync();
            return ApiResult<IEnumerable<SystemConfigDto>>.Success((int)ApiStatusCode.SUCCESS, "操作成功", items.AsEnumerable());
        }

        public async Task<ApiResult<SystemConfigDto>> GetByIdAsync(Guid id)
        {
            var config = await _db.AppSystemConfigs.FirstOrDefaultAsync(c => c.Id == id && !c.IsDelete);
            if (config is null)
                return ApiResult<SystemConfigDto>.Failed((int)ApiStatusCode.NOT_FOUND, "系统配置不存在");
            var dto = new SystemConfigDto
            {
                Id = config.Id,
                Key = config.Key,
                Value = config.Value ?? "",
                Description = config.Description,
                IsActive = config.IsActive,
                CreatedAt = config.CreatedAt,
                UpdatedAt = config.UpdatedAt
            };
            return ApiResult<SystemConfigDto>.Success((int)ApiStatusCode.SUCCESS, "操作成功", dto);
        }

        public async Task<ApiResult> CreateAsync(CreateSystemConfigDto dto)
        {
            if (string.IsNullOrWhiteSpace(dto.Key))
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "配置Key不能为空");
            var exists = await _db.AppSystemConfigs.AnyAsync(c => c.Key == dto.Key && !c.IsDelete);
            if (exists)
                return ApiResult.Failed((int)ApiStatusCode.CONFLICT, "配置Key已存在");
            var entity = new AppSystemConfig
            {
                Id = Guid.NewGuid(),
                Key = dto.Key,
                Value = dto.Value,
                Description = dto.Description,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow,
                IsActive = true,
                IsDelete = false
            };
            _db.AppSystemConfigs.Add(entity);
            await _db.SaveChangesAsync();
            return ApiResult.Success((int)ApiStatusCode.SUCCESS, "新增系统配置成功");
        }

        public async Task<ApiResult> UpdateAsync(Guid id, UpdateSystemConfigDto dto)
        {
            var config = await _db.AppSystemConfigs.FirstOrDefaultAsync(c => c.Id == id && !c.IsDelete);
            if (config is null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "系统配置不存在");
            config.Value = dto.Value;
            config.Description = dto.Description;
            config.IsActive = dto.IsActive;
            config.UpdatedAt = DateTime.UtcNow;
            await _db.SaveChangesAsync();
            return ApiResult.Success((int)ApiStatusCode.SUCCESS, "更新成功");
        }

        public async Task<ApiResult> DeleteAsync(Guid id)
        {
            var config = await _db.AppSystemConfigs.FirstOrDefaultAsync(c => c.Id == id && !c.IsDelete);
            if (config is null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "系统配置不存在");
            config.IsDelete = true;
            config.UpdatedAt = DateTime.UtcNow;
            await _db.SaveChangesAsync();
            return ApiResult.Success((int)ApiStatusCode.SUCCESS, "删除成功");
        }

        public async Task<ApiResult> EnableAsync(Guid id)
        {
            var config = await _db.AppSystemConfigs.FirstOrDefaultAsync(c => c.Id == id && !c.IsDelete);
            if (config is null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "系统配置不存在");
            if (config.IsActive)
                return ApiResult.Failed((int)ApiStatusCode.CONFLICT, "已是启用状态");
            config.IsActive = true;
            config.UpdatedAt = DateTime.UtcNow;
            await _db.SaveChangesAsync();
            return ApiResult.Success((int)ApiStatusCode.SUCCESS, "启用成功");
        }

        public async Task<ApiResult> DisableAsync(Guid id)
        {
            var config = await _db.AppSystemConfigs.FirstOrDefaultAsync(c => c.Id == id && !c.IsDelete);
            if (config is null)
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "系统配置不存在");
            if (!config.IsActive)
                return ApiResult.Failed((int)ApiStatusCode.CONFLICT, "已是禁用状态");
            config.IsActive = false;
            config.UpdatedAt = DateTime.UtcNow;
            await _db.SaveChangesAsync();
            return ApiResult.Success((int)ApiStatusCode.SUCCESS, "禁用成功");
        }

        public async Task<ApiResult<PagedResult<SystemConfigDto>>> GetPagedAsync(PagedQuery query)
        {
            var q = _db.AppSystemConfigs.Where(c => !c.IsDelete);
            if (!string.IsNullOrWhiteSpace(query.Search))
            {
                q = q.Where(c => c.Key.Contains(query.Search) || (c.Value ?? "").Contains(query.Search) || (c.Description ?? "").Contains(query.Search));
            }
            var total = await q.CountAsync();
            var items = await q.OrderByDescending(c => c.CreatedAt)
                .Skip((query.Page - 1) * query.Size)
                .Take(query.Size)
                .Select(c => new SystemConfigDto
                {
                    Id = c.Id,
                    Key = c.Key,
                    Value = c.Value ?? "",
                    Description = c.Description,
                    IsActive = c.IsActive,
                    CreatedAt = c.CreatedAt,
                    UpdatedAt = c.UpdatedAt
                })
                .ToListAsync();
            return ApiResult<PagedResult<SystemConfigDto>>.Success(
                (int)ApiStatusCode.SUCCESS, "操作成功",
                new PagedResult<SystemConfigDto>(items, total, query.Page, query.Size)
            );
        }
    }
} 